package com.learn.demo.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadLocal示例
 *
 * @author banjiawei
 * @date 2021/04/25
 */
public class ThreadLocalDemo {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println("当前线程："+Thread.currentThread().getName()+",获取的id为:"+ThreadId.getId());
            }).start();
        }
    }

    static class ThreadId{
        private static final AtomicInteger netxId = new AtomicInteger(0);
        private static final ThreadLocal<Integer> threadId = ThreadLocal.withInitial(() -> netxId.getAndIncrement());
        public static int getId(){
            return threadId.get();
        }
    }
}
